// -*- coding: utf-8 -*-
frappe.ui.form.on('Scrap Pickup List', {
    refresh: function(frm) {
        // 添加自定义按钮
        if (frm.doc.docstatus === 0) {
            frm.add_custom_button(__('生成待取清单'), function() {
                generate_pickup_list(frm);
            }, __('操作'));
        }
        
        if (frm.doc.docstatus === 1) {
            if (frm.doc.status === '待取') {
                frm.add_custom_button(__('标记为已取'), function() {
                    mark_as_picked(frm);
                }, __('操作'));
            }
            
            if (frm.doc.status === '已取') {
                frm.add_custom_button(__('标记为已完成'), function() {
                    mark_as_completed(frm);
                }, __('操作'));
                
                frm.add_custom_button(__('重置为待取'), function() {
                    reset_to_pending(frm);
                }, __('操作'));
            }
            
            frm.add_custom_button(__('查看事务记录'), function() {
                view_transaction_history(frm);
            }, __('查看'));
            
            frm.add_custom_button(__('打印待取清单'), function() {
                print_pickup_list(frm);
            }, __('查看'));
        }
    },
    
    warehouse: function(frm) {
        // 仓库变更时，更新子表中的库位过滤器
        if (frm.doc.warehouse) {
            frm.fields_dict['scrap_materials'].grid.get_field('location').get_query = function() {
                return {
                    filters: {
                        'warehouse': frm.doc.warehouse,
                        'status': '启用'
                    }
                };
            };
        }
    },
    
    scrap_materials: function(frm) {
        // 余料列表变更时，计算总数量
        calculate_total_quantity(frm);
    },
    
    pickup_list_id: function(frm) {
        // 格式化待取清单编号
        if (frm.doc.pickup_list_id) {
            // 确保格式为 SPL-YYYYMMDD-NNNN
            let formatted_id = frm.doc.pickup_list_id.toUpperCase();
            if (!formatted_id.match(/^SPL-\d{8}-\d{4,}$/)) {
                // 如果格式不正确，可以在这里进行格式化
                // 这里仅做提示
                frappe.msgprint({
                    title: '格式提示',
                    message: '建议的格式为: SPL-YYYYMMDD-NNNN',
                    indicator: 'orange'
                });
            }
            frm.set_value('pickup_list_id', formatted_id);
        }
    },
    
    onload: function(frm) {
        // 设置子表字段的过滤器
        if (frm.doc.warehouse) {
            frm.fields_dict['scrap_materials'].grid.get_field('location').get_query = function() {
                return {
                    filters: {
                        'warehouse': frm.doc.warehouse,
                        'status': '启用'
                    }
                };
            };
        }
        
        // 设置余料字段的过滤器
        frm.fields_dict['scrap_materials'].grid.get_field('scrap_material').get_query = function() {
            return {
                filters: {
                    'status': '可用'
                }
            };
        };
    },
    
    before_save: function(frm) {
        // 保存前计算总数量
        calculate_total_quantity(frm);
    }
});

// 子表事件
frappe.ui.form.on('Scrap Pickup List Item', {
    scrap_material: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.scrap_material) {
            // 获取余料信息并填充到子表
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Material',
                    filters: { name: row.scrap_material },
                    fieldname: ['material_type', 'material_name', 'color', 'length', 'width', 'thickness', 'unit', 'location', 'quantity']
                },
                callback: function(r) {
                    if (r.message) {
                        frappe.model.set_value(cdt, cdn, 'material_type', r.message.material_type);
                        frappe.model.set_value(cdt, cdn, 'material_name', r.message.material_name);
                        frappe.model.set_value(cdt, cdn, 'color', r.message.color);
                        frappe.model.set_value(cdt, cdn, 'length', r.message.length);
                        frappe.model.set_value(cdt, cdn, 'width', r.message.width);
                        frappe.model.set_value(cdt, cdn, 'thickness', r.message.thickness);
                        frappe.model.set_value(cdt, cdn, 'unit', r.message.unit);
                        frappe.model.set_value(cdt, cdn, 'location', r.message.location);
                        frappe.model.set_value(cdt, cdn, 'available_quantity', r.message.quantity);
                        
                        // 设置默认数量为可用数量
                        frappe.model.set_value(cdt, cdn, 'quantity', r.message.quantity);
                    }
                }
            });
        }
    },
    
    location: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.location) {
            // 验证库位状态和所属仓库
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Location',
                    filters: { name: row.location },
                    fieldname: ['status', 'warehouse']
                },
                callback: function(r) {
                    if (r.message) {
                        if (r.message.status !== '启用') {
                            frappe.msgprint({
                                title: '库位状态错误',
                                message: `库位 ${row.location} 状态为 ${r.message.status}，无法使用`,
                                indicator: 'red'
                            });
                            frappe.model.set_value(cdt, cdn, 'location', '');
                            return;
                        }
                        
                        if (frm.doc.warehouse && r.message.warehouse !== frm.doc.warehouse) {
                            frappe.msgprint({
                                title: '仓库不匹配',
                                message: `库位 ${row.location} 属于仓库 ${r.message.warehouse}，与当前仓库 ${frm.doc.warehouse} 不匹配`,
                                indicator: 'red'
                            });
                            frappe.model.set_value(cdt, cdn, 'location', '');
                            return;
                        }
                    }
                }
            });
        }
    },
    
    quantity: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.quantity && row.scrap_material) {
            // 验证数量是否超过可用数量
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Material',
                    filters: { name: row.scrap_material },
                    fieldname: ['quantity']
                },
                callback: function(r) {
                    if (r.message && flt(row.quantity) > flt(r.message.quantity)) {
                        frappe.msgprint({
                            title: '数量超过可用数量',
                            message: `余料 ${row.scrap_material} 可用数量为 ${r.message.quantity}，不能超过此数量`,
                            indicator: 'red'
                        });
                        frappe.model.set_value(cdt, cdn, 'quantity', r.message.quantity);
                    }
                }
            });
        }
        
        // 计算总数量
        calculate_total_quantity(frm);
    },
    
    status: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.status === '已取' && !row.picked_quantity) {
            // 如果状态为已取，但未设置已取数量，则设置为数量
            frappe.model.set_value(cdt, cdn, 'picked_quantity', row.quantity);
        }
        
        // 检查是否所有项都已取
        check_all_items_picked(frm);
    },
    
    scrap_materials_remove: function(frm) {
        // 删除行后重新计算总数量
        calculate_total_quantity(frm);
    }
});

// 辅助函数
function calculate_total_quantity(frm) {
    let total_quantity = 0;
    $.each(frm.doc.scrap_materials || [], function(i, d) {
        total_quantity += flt(d.quantity);
    });
    frm.set_value('total_quantity', total_quantity);
}

function check_all_items_picked(frm) {
    let all_picked = true;
    $.each(frm.doc.scrap_materials || [], function(i, d) {
        if (d.status !== '已取') {
            all_picked = false;
            return false;
        }
    });
    
    // 如果所有项都已取，则可以标记为已完成
    if (all_picked && frm.doc.status === '已取') {
        frm.add_custom_button(__('标记为已完成'), function() {
            mark_as_completed(frm);
        }, __('操作'));
    }
}

function mark_as_picked(frm) {
    frappe.call({
        method: 'scrap_management.scrap_management.doctype.scrap_pickup_list.scrap_pickup_list.mark_as_picked',
        args: {
            docname: frm.doc.name
        },
        callback: function(r) {
            if (r.message) {
                frappe.show_alert({ message: '已标记为已取', indicator: 'green' });
                frm.reload_doc();
            }
        }
    });
}

function mark_as_completed(frm) {
    frappe.call({
        method: 'scrap_management.scrap_management.doctype.scrap_pickup_list.scrap_pickup_list.mark_as_completed',
        args: {
            docname: frm.doc.name
        },
        callback: function(r) {
            if (r.message) {
                frappe.show_alert({ message: '已标记为已完成', indicator: 'green' });
                frm.reload_doc();
            }
        }
    });
}

function reset_to_pending(frm) {
    frappe.confirm('确定要重置为待取状态吗？这将清除已取和已完成信息。', function() {
        frappe.call({
            method: 'scrap_management.scrap_management.doctype.scrap_pickup_list.scrap_pickup_list.reset_to_pending',
            args: {
                docname: frm.doc.name
            },
            callback: function(r) {
                if (r.message) {
                    frappe.show_alert({ message: '已重置为待取状态', indicator: 'green' });
                    frm.reload_doc();
                }
            }
        });
    });
}

function view_transaction_history(frm) {
    frappe.route_options = {
        'reference_doctype': 'Scrap Pickup List',
        'reference_name': frm.doc.name
    };
    frappe.set_route('List', 'Scrap Transaction');
}

function print_pickup_list(frm) {
    window.open(frappe.urllib.get_full_url('/printview?'
        + 'doctype=' + encodeURIComponent(frm.doc.doctype)
        + '&name=' + encodeURIComponent(frm.doc.name)
        + '&trigger_print=1'
        + '&format=' + encodeURIComponent('Standard')
        + '&no_letterhead=0'));
}

function generate_pickup_list(frm) {
    // 这里可以实现从其他单据生成待取清单的逻辑
    frappe.msgprint({
        title: '功能开发中',
        message: '从其他单据生成待取清单的功能正在开发中',
        indicator: 'blue'
    });
}

// 库位过滤函数
function get_location_filter_for_pickup_list(frm) {
    return {
        filters: {
            'warehouse': frm.doc.warehouse,
            'status': '启用'
        }
    };
}